package uk.co.cocking.getinline2.restlet;

import java.io.IOException;

import org.restlet.Restlet;
import org.restlet.data.Method;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;

import uk.co.cocking.getinline2.exceptions.ClientException;
import uk.co.cocking.getinline2.pipeline.Consumer;

public class StringForwardingRestlet extends Restlet {

	private final Consumer<String> pipeline;

	public StringForwardingRestlet(Consumer<String> pipeline) {
		this.pipeline = pipeline;
	}

	@Override
	public void handle(Request request, Response response) {
		try {
			pipeline.process(checkRequestForInput(request, response));
		} catch (Exception e) {
			response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		}
	}

	private String checkRequestForInput(Request request, Response response) throws ClientException, IOException {
		if (request.getMethod().equals(Method.GET)) {
			return request.getResourceRef().getLastSegment();
		}
		if (request.getMethod().equals(Method.POST)){
			return request.getEntity().getText();
		}	
		throw new ClientException("request must be GET or PUT");
	}
	
	
	
	

}
